﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Wwtfly.BBS.BackModels.Models.Users;
using Wwtfly.BBS.BackModels;
using System.Web.Routing;
using System.Web.Security;
using Wwtfly.BBS.BackModels.Models.Users.BBSPortalIdentity;
using Wwtfly.Utility;
using Wwtfly.BBS.BackBLL.Users;
using Wwtfly.BBS.BackModels.Models.Users.Right;
using Wwtfly.BBS.Enums.Common;
using Wwtfly.LoggerUtility;
using System.Web;
using Wwtfly.BBS.BackModels.Models;

namespace Wwtfly.BBS.BackControllers.Home
{

    /// <summary>
    /// 后台 父类 控件器
    /// </summary>
    public class BackBaseController : Controller
    {


        #region 属性
        /// <summary>
        /// 用户
        /// </summary>
        private BBSPortalIdentity _userInfo;

        /// <summary>
        /// 当前用户
        /// </summary>
        public new BBSPortalIdentity User
        {
            get { return _userInfo = base.User as BBSPortalIdentity; ; }
        }
        #endregion


        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            //检查权限..
            if (!this.CheckPageRight())
            {
                //指向到 权限错误界面..
                UrlHelper url = new UrlHelper(filterContext.RequestContext);
                List<string> list1 = new List<string>();
                list1.Add("你没有操作的权限!");
                List<string> list2 = new List<string>();
                list2.Add(ContentHelper.CreateA("返回首页", url.Action("Index", "BackHome")));
                list2.Add(ContentHelper.CreateA("重新登陆", url.Action("SignOut", "BackHome")));
                ErrorViewModel viewModel = new ErrorViewModel() { InfoList = list1, UrlList = list2, Title = "出错啦" };
                ViewDataDictionary vdd = new ViewDataDictionary(viewModel);
                filterContext.Result = new ViewResult() { ViewName = "BackError", ViewData = vdd };
            }
        }

            /// <summary>
        /// 读出搜索条件
        /// </summary>
        /// <typeparam name="T">搜索条件类型</typeparam>
        /// <param name="key">存入的键值</param> 
        /// <returns>搜索条件类实例</returns>
        protected T RestoreSearch<T>(string key = null) where T : BaseSearchModel
        {
            T search = default(T);
            key = key ?? this.RightCode ?? "SearchKey";
            search = (TempData[key] as T);
            this.SaveSearch(search, key);
            return search ?? Activator.CreateInstance<T>();
        }
        /// <summary>
        /// 存入搜索条件
        /// </summary>
        /// <param name="searchField">搜索条件类</param>
        /// <param name="key">存入的键值</param> 
        protected void SaveSearch(object searchField, string key = null)
        {
            key = key ?? this.RightCode ?? "SearchKey";
            TempData[key] = searchField;
        }

        /// <summary>
        /// 删除搜索条件
        /// </summary>
        /// <param name="key">存入的键值</param> 
        protected void ResetSearch(string key = null)
        {
            key = key ?? this.RightCode ?? "SearchKey";
            TempData[key] = null;
        }


        protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);

            if (Request.IsAuthenticated)
            {
                FormsIdentity fi = User.Identity as FormsIdentity;

                User.SetCurrentUser(LoginUserUtil.GetCurrentUserInfo<UsersModel>());
                if (User.UserInfo == null)
                {
                    User.SetCurrentUser(UsersBLL.GetUsersInfo(fi.Name));
                    Session[LoginUserUtil.LOGIN_USER] = User.UserInfo;
                }

                //判断用户是否具有 后台权限(角色), 没有权限,则是非法进入到后面界面,直接销毁凭证...
                if (!HasBackRight(User.UserInfo))
                {
                    //跳转到 登陆界面..
                    FormsAuthentication.SignOut();
                    Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
                    this.Session.Abandon();
                    Response.Redirect(Url.Content(LoginUserUtil.ForeLoginUrl));
                    return;
                }
            }
            else
            {

            }
        }

        

        /// <summary>
        /// 判断 用户是否具有 后台用户角色..
        /// </summary>
        /// <returns></returns>
        public bool HasBackRight(UsersModel users)
        {
            if (users == null)
            {
                return false;
            }
            if (!users.IsSuperMan)
            {
                var result = users.UARoleInfoList.FirstOrDefault(m => m.RoleType ==
              ModuleTypeEnum.BACKBBS.ToString());
                return result != null;
            }
            return true;
        }

        /// <summary>
        /// 检查权限... 支持多个. 以,逗号隔开..
        /// </summary>
        protected virtual bool CheckPageRight()
        {
            bool has = User.UserInfo.IsSuperMan ? true : HasCheckPageRight();
            if (!has)
            {
                LoggerManage.Error(new LogMessageParams()
                {
                    ModuleID = "BackBaseController",
                    FuncCode = "Initialize",
                    Level = AppErrorLevel.EROR,
                    ErrCode = "0x0",
                    logMessage = "用户无权限 rightCode:" + RightCode,
                    ProgramName = "Wwtilfy.BBS"
                });

            }
            return has;
        }

        /// <summary>
        /// 是否有权限..
        /// </summary>
        /// <returns></returns>
        private bool HasCheckPageRight()
        {
            bool result = false;
            if (string.IsNullOrEmpty(RightCode))
            {
                result = true;
                return result;
            }
            else
            {
                string[] pageRightCodeArry = RightCode.Split(',');
                //pageRightCodeArry
                if (pageRightCodeArry != null)
                {
                    if (pageRightCodeArry.Length == 1)
                    {
                        result = User.UserInfo.UARightInfoList.ContainsKey(RightCode);
                    }
                    else
                    {
                        for (int i = 0; i < pageRightCodeArry.Length; i++)
                        {
                            result = User.UserInfo.UARightInfoList.ContainsKey(pageRightCodeArry[i]);
                            if (result == true)
                            {
                                break;
                            }
                        }
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 权限Code
        /// </summary>
        protected virtual string RightCode { get; private set; }

        /// <summary>
        /// 输出错误处理
        /// </summary>
        /// <param name="error">用于显示的强类型消息 ViewModel</param>
        /// <returns>ActionResult</returns>
        protected ActionResult ErrorResult(ErrorViewModel error)
        {
            return View("ErrorAjax", error);
        }
    }
}

